﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FluentNHibernate.Cfg.Db;
using FluentNHibernate.Cfg;
using NHibernate;
using NHibernate.Cfg;
using springProject;

namespace Models.DataAccess
{
    public class NHibernateHelper
    {
        private static ISessionFactory _sessionFactory;

        private static Configuration BuildDatabaseConfig()
        {
            var dbConfig = MsSqlConfiguration.MsSql2008
                .ConnectionString(System.Configuration.ConfigurationManager.ConnectionStrings["SpringEntities"].ConnectionString);

            return Fluently.Configure()
            .Database(dbConfig)
            .Mappings(m => m.FluentMappings.AddFromAssemblyOf<MvcApplication>())
                //.ExposeConfiguration(config => config.SetProperty("current_session_context_class", "web"))
            .ExposeConfiguration(config => config.SetProperty("current_session_context_class", "web"))
            .BuildConfiguration();
        }
        
        
        private static ISessionFactory SessionFactory
        {
            get
            {
                if (_sessionFactory == null)
                {
                    var configuration = BuildDatabaseConfig();
                    _sessionFactory = configuration.BuildSessionFactory();
                }
                return _sessionFactory;
            }
        }

        public static ISession OpenSession()
        {
            return SessionFactory.OpenSession();
        }
    }
}